package dep

import (
	"context"
	"fmt"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
	"go.opentelemetry.io/otel/trace"
)

func NewTracerProvider(textMapPropagator propagation.TextMapPropagator) (trace.TracerProvider, error) {
	// meta := bc.Metadata
	// traceConf := bc.Otel.Trace

	// opts := []otlptracehttp.Option{otlptracehttp.WithEndpoint(traceConf.Endpoint)}
	// if traceConf.Insecure { //http方案而不是https
	// 	opts = append(opts, otlptracehttp.WithInsecure())
	// }
	// client := otlptracehttp.NewClient(opts...)
	// exp, err := otlptrace.New(ctx, client)
	// if err != nil {
	// 	return nil, err
	// }

	tp := sdktrace.NewTracerProvider(
		// sdktrace.WithBatcher(exp),
		sdktrace.WithResource(
			resource.NewWithAttributes(
				semconv.SchemaURL,
				semconv.ServiceNameKey.String("servceName名"),
				attribute.String("environment", "dev"),
			),
		),
	)

	// otel.SetTracerProvider(tp)
	// otel.SetTextMapPropagator(textMapPropagator)

	return tp, nil
}

// func NewTracer(tp trace.TracerProvider) (trace.Tracer, error) {
// 	// meta := bc.Metadata
// 	return tp.Tracer("NewTracerservceName名"), nil
// }

func NewTextMapPropagator() propagation.TextMapPropagator {
	// cpg := new(customPropagator)
	return propagation.NewCompositeTextMapPropagator(
	// cpg,
	// tracing.Metadata{},
	// propagation.Baggage{},
	// propagation.TraceContext{},
	)
}

// 自定义键
var customContextKey = "my-custom-key"

// 自定义传播器（简单示例，仅用于演示）
type customPropagator struct{}

func (p *customPropagator) Fields() []string {
	return []string{customContextKey} // 返回要传播的字段列表
}

func (p *customPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
	if value := ctx.Value(customContextKey); value != nil {
		fmt.Println("Inject", value)
		carrier.Set(customContextKey, value.(string)) // 将值注入到载体中
	}
}

func (p *customPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
	if value := carrier.Get(customContextKey); value != "" { //从header头里取出自定义traceid
		sc := trace.SpanContextFromContext(ctx)
		generateTrace, _ := trace.TraceIDFromHex(value) // 80f198ee56343ba864fe8b2a57d3eff7要满足一定的规则1、长度32，2、0-9a-f
		fmt.Println("generateTrace", generateTrace)
		ctx = trace.ContextWithRemoteSpanContext(ctx, trace.NewSpanContext(trace.SpanContextConfig{
			TraceID: generateTrace,
			SpanID:  sc.SpanID(),
		}))
		return context.WithValue(ctx, customContextKey, value) // 从载体中提取值并添加到上下文中
	} //TODO else的时候要创建一个新的
	return ctx
}
